package utils

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type MyClaims struct {
	Id int `json:"id"`
	jwt.StandardClaims
}

const TokenExpireDuration = time.Hour * 2

var mySecret = []byte("123456")

// GenToken 生成JWT
func GenToken(id int) (string, error) {
	c := MyClaims{
		id,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(),
			Issuer:    "balance",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	/*fmt.Println("secret: ", mySecret)
	fmt.Println("token: ", token)*/
	tmp, err := token.SignedString(mySecret)
	/*fmt.Println("生成的token令牌：", tmp)*/
	return tmp, err
}

func ParseToken(tokenSring string) (*MyClaims, error) {
	token, err := jwt.ParseWithClaims(tokenSring, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySecret, nil
	})
	if err != nil {
		return nil, err
	}
	if Claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
		return Claims, nil
	}
	return nil, errors.New("invalid token")
}
